<template>
  <s-modal
    title="添加"
    :visible="visible"
    width="800px"
    ok-text="保存"
    :confirm-loading="confirmLoading"
    :closable="!confirmLoading"
    @ok="save()"
    @cancel="
      () => {
        if (!confirmLoading) {
          visible = false
        }
      }
    "
  >
    <div style="height: 400px">
      <s-scroll>
        <s-form ref="form" :value="formValue">
          <s-dynamic-form :items="items" :form="formValue" />
        </s-form>
      </s-scroll>
    </div>
  </s-modal>
</template>

<script>
export default {
  name: 'Add',
  props: {
    items: {
      type: Array,
      default: () => {
        return []
      }
    },
    initValue: {
      type: Object,
      default: () => {
        return {}
      }
    },
    success: {
      type: Function,
      required: false,
      default: () => {}
    }
  },
  data() {
    return {
      formValue: this.initValue,
      confirmLoading: false,
      visible: false
    }
  },
  watch: {
    initValue: {
      handler: function (val, oldVal) {
        this.formValue = val
      },
      deep: true
    }
  },
  methods: {
    open() {
      this.visible = true
    },
    save() {
      const form = this.$refs.form
      form.validate((values) => {
        const data = {
          modelForm: values
        }
        this.confirmLoading = true
        this.$api
          .PUT('/code/model/insert', data)
          .then((res) => {
            this.confirmLoading = false
            this.visible = false
            this.$emit('success')
            this.$message.info(res.msg)
          })
          .catch(() => {
            this.confirmLoading = false
          })
      })
    }
  }
}
</script>

<style lang="less" scoped></style>
